<template>
    <div class="qilin-QilinUploadImage">
        <el-upload
            ref="QilinUploadImage"
            :action="ownUploadImageConifg.action || '#' "
            :list-type="ownUploadImageConifg.listType || 'picture-card' "
            :auto-upload="ownUploadImageConifg.autoUpload || false "
            :limit="ownUploadImageConifg.limit || (ownUploadImageConifg.multiple ? 6 : 1 ) "
            :drag="ownUploadImageConifg.drag || true "
            :file-list="ownUploadImageConifg.fileList || [] "
            :multiple="ownUploadImageConifg.multiple || false "
            :show-file-list="true"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
        >
            <!-- <el-icon><CameraFilled /></el-icon> -->
            <i :class="['iconfont',ownUploadImageConifg.iconfont || 'icon-shangchuan-shangchuantupian' ]"></i>
            <div class="image-tip-text">上传图片</div>
        </el-upload>
        <!-- <span class="qilin-QilinUploadImage-tip" v-show="!!ownUploadImageConifg.fileTypeText">{{ownUploadImageConifg.fileTypeText || ""}}</span> -->
        <span class="qilin-QilinUploadImage-tip" >{{ownUploadImageConifg.fileTypeText || "(支持jpg、png、jpeg等图片格式)"}}</span>
    </div>
    <QilinDialog v-model:dialogConfig="dialogConfig" @handleClose="closeDialog">
        <el-image
            style="width:100%;height:500px;"
            :src="currentImage"
            :preview-src-list="ownUploadImageConifg.fileList.map((item)=>{
                return imageIp+item[ownUploadImageConifg.serverUrl || 'fileName'];
            })"
            :initial-index="initialIndex"
            fit="scale-down"
        ></el-image>
    </QilinDialog>
</template>

<script setup>
// import {uploadFiles} from "@/api/index.js";

/*
    数据变量定义区域
*/
// 当前预览图片url
let currentImage=ref("");
// 当前预览图片索引位置
let initialIndex=ref(0);
// 获取上传元素DOM
let QilinUploadImage=ref(null);


/*
    计算属性等代码区域
*/
// 接收来自父组件的传参
const propsValue=defineProps({
    uploadImageConfig:{
        type:Object,
        default(){
            return {
                // 组件自身的默认配置
                action:"#", //文件上传至服务器url
                listType:"picture-card", //文件列表类型
                autoUpload:false, //是否自动上传
                limit:1, //文件允许上传数量
                fileList:[], //默认上传文件
                multiple:false, //是否支持多选文件
                drag:true, //是否启用拖拽上传
                showFileList:false, //是否显示已上传文件列表
                uploadText:"拖入此处上传或点击上传", //上传文字说明
                fileTypeText:"（支持png、jpg、jpeg、gif文件格式）", //支持格式文字说明
                fileType:["png","jpg","jpeg","gif"], //支持上传的文件类型
                fileSize:20 * 1000 * 1000, //文件上传大小限制20M之内默认
                iconfont:"icon-shangchuan-shangchuantupian", //默认的显示图标
                uploadType:"server", //上传图片方式，默认为先上传至服务器,raw表示不上传至服务器
                serverOriginalName:"originalFilename", //文件上传至后端，返回的原始文件名称
                serverName:"newFileName", //文件上传至后端，返回的文件名称--用以回显文件的名称
                serverUrl:"fileName", //文件上传至后端，返回的文件url地址--用以回显文件的url
            };
        }
    },
    fileList:{ //用以回显
        type:[Array,String],
        default(){
            return []
        }
    }
});

// 暴露父组件自定义方法
const emits=defineEmits(["update:uploadImageConfig","success"]);

// 组件自身的配置项
let ownUploadImageConifg=computed({
    get(){
        propsValue.uploadImageConfig.fileList=propsValue.fileList ? ( typeof propsValue.fileList === "string" ? JSON.parse(propsValue.fileList) : propsValue.fileList || [] ) : [] ;
        // propsValue.uploadImageConfig.fileList=typeof propsValue.fileList === "string" ? JSON.parse(propsValue.fileList) : propsValue.fileList || [] ;
        // propsValue.uploadImageConfig.fileList=propsValue.fileList || [];
        return propsValue.uploadImageConfig;
    },
    set(val){
        emits("update:uploadImageConfig",val);
    }
});


/*
    逻辑脚本代码区域
*/
// 文件上传之前的事件监听--仅在action为服务器资源地址时生效
const handleBeforeUpload=(file)=>{
    // console.log(file);
    const index=file.name.lastIndexOf(".");
    const fileType=file.name.slice(index+1);
    if(ownUploadImageConifg.value.fileType && !ownUploadImageConifg.value.fileType.includes(fileType)){
        ElMessage({
            message:"请上传符合格式要求的文件",
            type:"warning"
        });
        return false;
    }else if(file.size > (ownUploadImageConifg.value.fileSize || 20 * 1000 * 1000) ){
        ElMessage({
            message:"文件大小超过限制",
            type:"warning"
        });
        return false;
    };
};
// 文件上传状态改变事件监听
const handleChange=(file)=>{
    const index=file.name.lastIndexOf(".");
    const fileType=file.name.slice(index+1);
    if(ownUploadImageConifg.value.fileType && !ownUploadImageConifg.value.fileType.includes(fileType)){
        ElMessage({
            message:"请上传符合格式要求的文件",
            type:"warning"
        });
        nextTick(()=>{
            QilinUploadImage.value.handleRemove(file);
        });
    }else if(file.size > (ownUploadImageConifg.value.fileSize || 20 * 1000 * 1000)){
        ElMessage({
            message:"文件大小超过限制",
            type:"warning"
        });
        nextTick(()=>{
            QilinUploadImage.value.handleRemove(file);
        });
    }else{
        if(ownUploadImageConifg.value.uploadType === "raw"){ //不上传至服务器方式
            ownUploadImageConifg.value.fileList.push({
                raw:file.raw,
                name:file.name
            });
            emits("success",ownUploadImageConifg.value.fileList);
        }else{ // 上传至服务器方式
            let formData=new FormData();
            formData.append("file",file.raw);
            // uploadFiles(formData).then((res)=>{
            //     if(res.code === 200){
            //         ownUploadImageConifg.value.fileList.push(res.data);
            //         emits("success",ownUploadImageConifg.value.fileList);
            //     }else{
            //         // 上传文件至服务器失败时需手动清除本地列表文件
            //         nextTick(()=>{
            //             QilinUploadImage.value.handleRemove(file);
            //         });
            //         ElMessage({
            //             message:"文件上传失败",
            //             type:"error"
            //         });
            //     };
            // }).catch(()=>{
            //     nextTick(()=>{
            //         QilinUploadImage.value.handleRemove(file);
            //     });
            // });
        };
    };
};
// 文件超出限制事件监听
const handleExceed=(file,files)=>{
    // console.log(file,files);
    ElMessage({
        message:"文件上传数量不能大于"+(ownUploadImageConifg.value.limit || (ownUploadImageConifg.value.multiple ? 6 : 1 ) )+"个",
        type:"warning"
    });
};
// 文件预览事件监听
const handlePreview=(file)=>{
    if(ownUploadImageConifg.value.uploadType === "raw"){ //若文件不先上传至服务器

    }else{ //若文件先上传至服务器
        if(file.raw){ //若是本地上传后直接预览
            currentImage.value=file.url;
            initialIndex.value=ownUploadImageConifg.value.fileList.findIndex((item)=>{
                return item[ownUploadImageConifg.value.serverOriginalName || "originalFilename"] === file.name;
            });
        }else{ //线上后台数据回显预览
            currentImage.value=file[ownUploadImageConifg.value.serverUrl || "fileName"];
            initialIndex.value=ownUploadImageConifg.value.fileList.findIndex((item)=>{
                return item[ownUploadImageConifg.value.serverUrl || "fileName"] === currentImage.value;
            });
            currentImage.value=imageIp+file[ownUploadImageConifg.value.serverUrl || "fileName"];
        };
    };
    dialogConfig.isShow=true;
};
// 文件删除事件监听
const handleRemove=(file,files)=>{
    let index=-1;
    if(ownUploadImageConifg.value.uploadType === "raw"){ //若文件不先上传至服务器

    }else{ //若文件先上传至服务器
        if(file.raw){ //若是本地上传后直接删除
            index=ownUploadImageConifg.value.fileList.findIndex((item)=>{
                return item[ownUploadImageConifg.value.serverOriginalName || "originalFilename"] === file.name;
            });
        }else{ //线上后台数据删除
            index=ownUploadImageConifg.value.fileList.findIndex((item)=>{
                return item[ownUploadImageConifg.value.serverOriginalName || "originalFilename"] === file[ownUploadImageConifg.value.serverOriginalName || "originalFilename"];
            });
        };
    };
    if(index !== -1){
        ownUploadImageConifg.value.fileList.splice(index,1);
        emits("success",ownUploadImageConifg.value.fileList);
    };
};
// 关闭预览弹窗事件监听
const closeDialog=()=>{
    dialogConfig.isShow=false;
};

// 图片预览弹窗配置项
let dialogConfig=reactive({
    isShow:false,
    title:"图片预览",
    isHideFooter:true
});


/*
    生命周期等代码区域
*/

</script>

<style lang="scss" scoped>
.qilin-QilinUploadImage{
    width:100%;
    >.qilin-QilinUploadImage-tip{
        color:$text-color-45;
    }
    >.qilin-QilinUploadImage-list{
        width:65%;
        >.qilin-QilinUploadImage-list-item{
            display:flex;
            align-items:center;
            justify-content: space-between;
            margin:10px 0;
            line-height:1;
            >img{
                width:15px;
                height:15px;
            }
            >span{
                color:$primary-text-color;
                margin:0 6px;
                cursor:pointer;
                flex:1;
                white-space:nowrap;
                overflow:hidden;
                text-overflow:ellipsis;
            }
        }
    }
}
</style>
